<template>
    <div class="table">
<!--        <div class="crumbs">-->
<!--            <el-breadcrumb separator="/">-->
<!--                <el-breadcrumb-item><i class="el-icon-lx-cascades"></i> 账户管理</el-breadcrumb-item>-->
<!--            </el-breadcrumb>-->
<!--        </div>-->
        <div class="container">
            <div class="handle-box" style="margin:15px 0;">
                <el-button type="primary" @click="addCount">新增账户</el-button>
                <el-button type="success" @click="editCount">修改账户</el-button>
                <el-button type="danger" @click="delCount">删除账户</el-button>
            </div>
            <el-table :data="tableData" border stripe class="table" @selection-change="handleSelectionChange" ref="multipleTable" @row-click="handleRowClick">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="account" align="center" label="账号">
                </el-table-column>
                <el-table-column prop="name" align="center" label="姓名">
                </el-table-column>
                <!--<el-table-column prop="roleName" align="center" label="角色">-->
                <!--</el-table-column>-->
                <el-table-column prop="createTime" align="center" :formatter="formatTime" label="日期">
                </el-table-column>
                <el-table-column prop="phone" align="center" label="电话">
                </el-table-column>
                <el-table-column prop="email" align="center" label="邮箱">
                </el-table-column>
                <el-table-column prop="orgId" align="center" :formatter="formatOrg" label="所属组织" v-if="loginUserInfo.roleValue == 1">
                </el-table-column>
                <el-table-column prop="" label="操作" fixed="right" width="200">
                    <template slot-scope="scope" v-if="scope.row.roleValue!=userRoleValue">
                        <template v-if="scope.row.roleValue!=8">
                            <el-button v-if="scope.row.orgId" type="primary" size="mini" @click="unbindBtn(scope.row)">解除组织</el-button>
                            <el-button v-else type="primary" size="mini" @click="bindLink(scope.row)">划分组织</el-button>
                        </template>
                        <el-button type="primary" size="mini" @click="bindLinkEqu(scope.row)">划分设备</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background @current-change="handleCurrentChange" layout="prev, pager, next" :total="page_total" :page-size="page_size">
                </el-pagination>
            </div>
        </div>

        <!-- 新增人员弹出框 -->
        <el-dialog :title="diologTitle" :visible.sync="addVisible" width="70%" @open="show">
            <el-form :model="form" label-width="80px" style="border: 1px solid #EBEEF5;margin-bottom: 10px;padding-top: 18px;">
                <el-form-item label="账户名称" class="limit-width">
                    <el-input v-model="form.account"></el-input>
                </el-form-item>
                <el-form-item label="密码" class="limit-width">
                    <el-input v-model="form.pwd"></el-input>
                </el-form-item>
                <el-form-item label="姓名" class="limit-width">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="性别" class="limit-width">
                    <el-select v-model="form.sex">
                        <el-option label="男" value="0"></el-option>
                        <el-option label="女" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" class="limit-width">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" class="limit-width">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <!--<el-form-item label="所属部门" class="limit-width">-->
                    <!--<el-input v-model="form.department"></el-input>-->
                <!--</el-form-item>-->
                <el-form-item label="备注" style="margin-left: 10%;margin-right: 10%;">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="form.remarks"></el-input>
                </el-form-item>
            </el-form>
            <!--<el-table height="250"-->
                      <!--border  stripe-->
                      <!--style="width: 100%" :data="roleData" class="table" ref="roleDataTable" @selection-change="styleSelectionChange" @row-click="handleroleDataClick">-->
                <!--<el-table-column type="selection" width="55" align="center"></el-table-column>-->
                <!--<el-table-column prop="roleName" label="角色名称" align="center">-->
                <!--</el-table-column>-->
                <!--<el-table-column prop="remark" label="备注" align="center">-->
                <!--</el-table-column>-->
            <!--</el-table>-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit('form')">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteRow">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 解绑提示框 -->
        <el-dialog title="提示" :visible.sync="unbindVisible" width="300px" center>
            <div class="del-dialog-cnt">确定解除该用户的组织机构？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="unbindVisible = false">取 消</el-button>
                <el-button type="primary" @click="unbindLink">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 账户划组织 -->
        <el-dialog title="划分组织" :visible.sync="bindVisible" width="70%" @open="show">
            <div>
                <el-tree
                        :data="unbindOrgs"
                        :props="props"
                        highlight-current
                        default-expand-all
                        check-on-click-node
                        check-strictly
                        show-checkbox
                        node-key="id"
                        :default-checked-keys="[curr_id]"
                        ref="tree"
                        @node-expand="handleNodeClick"
                >
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span>{{ node.label }}</span>
                    </span>
                </el-tree>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="bindVisible = false">取 消</el-button>
                <el-button type="primary" @click="bindOrgUser">确 定</el-button>
            </span>
        </el-dialog>
        <!--设备划组-->
        <el-dialog title="设备组划分" :visible.sync="isShowDivision" width="90%" >
            <div style="">
                <v-edivision :parentData="parentData" :isShowDivision="isShowDivision"></v-edivision>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="isShowDivision = false">返 回</el-button>
                <!--                <el-button type="primary" @click="saveEdit('form')">确 定</el-button>-->
            </span>
        </el-dialog>
    </div>
</template>
<script>
    import { regionalRoot,getSubOrgList,countManger,addCountManger,editCountManger,delCountManger ,
        assignOrgToUser,getUnassignedOrgList,getRoleList} from '../../../api/index';
    import {famatDatesTimes,regPhoneNum,regEmailNum,getSimpleCheckedNodes} from '../../common/com';
    import vEdivision from '../dataDictionary/equipmentDivision.vue';
    export default {
        name: "UserCountManger",
        components:{
           vEdivision
        },
        data() {
            return {
                tableData: [],
                roleData:[],
                cur_page: 1,
                page_size:10,
                page_total:1,
                multipleSelection: [],
                diologTitle:'新增账户',
                styleSelection:[],
                delVisible: false,
                addVisible:false,
                form: {
                    account: '',
                    pwd: '',
                    name: '',
                    sex:'0',
                    phone:'',
                    department:'',
                    email:'',
                    remarks:''
                },
                isEditInfo:false,
                tagsList:[],
                props: {
                    label: 'orgName',
                    // children: 'zones',
                    // isLeaf: 'leaf'
                },
                lazyInitData:[],
                lazyNode:null,
                clickedId:'',
                curr_id:"",
                clickNode:null,
                clikData:null,
                demoData:'',
                bindVisible:false,
                unbindOrgs:[],
                unbindIfo:'',
                unbindVisible:false,
                currUserId:'',
                loginUserInfo:{roleValue:1},
                isShowDivision:false,
                parentData:'',
                userRoleValue:'',

            }
        },
        created() {
            this.getTreeData()
            this.getData();
            this.getRoleDataList();
            this.userRoleValue = localStorage.getItem('uer_role_value')
        },
        computed: {

        },

        methods: {
            //获取数据
            getTreeData(){
                regionalRoot({

                }).then((res) =>{
                    // console.log(res)
                    var dataArr = new Array();
                    dataArr[0] = res.expandData.root;
                    dataArr[0]['disabled'] = true //默认gen节点不可选择
                    dataArr[0]['children'] = res.expandData.childrens;
                    this.tagsList = dataArr;
                    this.clickedId = this.tagsList[0].id;
                    // console.log(dataArr)
                })
            },
            loadNode(node, resolve) {
                this.lazyNode = node;
                this.lazyResolve = resolve;
                if (node.level === 0) {
                    return resolve(this.tagsList);
                }
                // if (node.level > 1) return resolve([]);

                setTimeout(() => {
                    getSubOrgList({
                        pid:this.clickedId
                    }).then((res)=>{
                        this.lazyInitData = res.datas;
                        resolve(this.lazyInitData);
                    })
                }, 500);
            },
            //树的节点点击事件
            handleNodeClick(data,node) {
                this.clikData = data;
                this.clickNode = node;
                if(data.pid === 0){
                    this.clickedId = data.id;
                    this.demoData = data;
                    this.demoData['pname'] = data.orgName;
                    return ;
                }
                this.clickedId = data.id;
                this.demoData = data;
                this.demoData['pname'] = node.parent.data.orgName;
            },
            // 分页导航
            handleCurrentChange(val) {
                this.cur_page = val;
                this.getData();
            },

            formatTime(row, column, cellValue, index){
                return famatDatesTimes(cellValue);
            },
            //获取角色数据
            getRoleDataList(){
                getRoleList({
                    pageNum:this.cur_page,
                    pageSize:this.page_size
                }).then((res)=>{
                    console.log(res);
                    this.roleData = res.list;

                })
            },
            // 获取数据
            getData() {
                countManger({
                    pageNum:this.cur_page,
                    pageSize:this.page_size
                }).then((res) => {
                    // console.log(res)
                    this.tableData = res.list;
                    this.page_total = res.total;
                    // console.log(JSON.stringify(this.tableData))
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
                console.log(this.multipleSelection)
            },
            //点击行触发，选中或不选中复选框
            handleRowClick(row, column, event){
                this.$refs.multipleTable.toggleRowSelection(row);
            },
            //点击角色行触发，选中或不选中复选框
            handleroleDataClick(row, column, event){
                this.$refs.roleDataTable.toggleRowSelection(row);
            },
            //新建账户划分角色，当前账户的后一个角色
            //2 超级管理员及厂家 ，4 管理员厂家的下级账户，8 管理员的下级账户
            formatRole(){
                if(this.userRoleValue == 2){
                    return 4
                }
                if(this.userRoleValue == 4){
                    return 8
                }
            },
            // 保存编辑
            saveEdit(formName) {
                // const orgList = getSimpleCheckedNodes(this.$refs.tree.store)
                // const orgList = this.$refs.tree.getCheckedNodes()
                // const orgIds = orgList.map(item => {
                //     return item.id
                // })

                if(this.formValidate(this.form)){
                    //如果是编辑的话
                    if(this.isEditInfo){
                        // this.multipleSelection[0].orgId = orgIds.length == 0 ? "":orgIds[0]
                        // this.multipleSelection[0].roleValue = this.styleSelection.length>0?this.styleSelection[0].bitValue:'';
                        editCountManger(this.multipleSelection[0]).then((res)=>{
                            if(res.success){
                                this.$message.success(res.message);
                                this.addVisible = false;
                                this.getData();
                            }else{
                                this.$message.error(res.message)
                            }
                        })
                        return;
                    }

                    //否则为新增
                    addCountManger({
                        "account":this.form.account,
                        // "department":this.form.department,
                        "email":this.form.email,
                        "phone":this.form.phone,
                        "pwd":this.form.pwd,
                        "remarks":this.form.remarks,
                        "sex":this.form.sex,
                        "name":this.form.name,
                        // "orgId": orgIds.length == 0? "" : orgIds[0],
                        "roleValue":this.formatRole()//this.styleSelection.length>0?this.styleSelection[0].bitValue:'',
                    }).then((res)=>{
                        console.log(res)
                        if(res.success){
                            this.addVisible = false;
                            this.$message.success(`添加成功`);
                            this.getData();
                        }else{
                            this.$message.error(res.message);
                        }
                    })
                    console.log(this.form)
                }
            },
            // 确定删除
            deleteRow(){
                var delCountId = new Array();
                for(var i=0;i<this.multipleSelection.length;i++){
                    delCountId.push(this.multipleSelection[i].id)
                }
                console.log(delCountId);
                delCountManger({
                    ids:delCountId
                }).then((res)=>{
                    console.log(res)
                    if(res.success){
                        this.$message.success('删除成功');
                        this.delVisible = false;
                        this.getData();
                    }else{
                        this.$message.error(res.message)
                    }
                })

            },
            //点击新增
            addCount(){
                this.curr_id = ""
                // this.getTreeData();
                this.addVisible = true;
                this.isEditInfo = false;
                this.diologTitle = '新增账户';
                this.form ={
                    account: '',
                    pwd: '',
                    name: '',
                    sex:'0',
                    phone:'',
                    department:'',
                    email:'',
                    remarks:''
                };
            },

            //点击修改
            editCount(){
                if(this.multipleSelection.length < 1){
                    this.$message.error('请选择需要修改的账户');
                }else
                if(this.multipleSelection.length == 1){
                    // this.getTreeData();
                    this.diologTitle = '修改账户';
                    this.addVisible = true;
                    this.isEditInfo = true;
                    this.form = this.multipleSelection[0];

                }else{
                    this.$message.error('一次只能修改一个账户');
                }

            },
            show () {
                if(!this.isEditInfo){
                    return ;
                }
                this.$nextTick(_ => {
                    // this.$refs.roleDataTable.clearSelection();
                    // this.$refs.roleDataTable.toggleRowSelection(this.roleData.find(d => parseInt(d.bitValue) === parseInt(this.multipleSelection[0].roleValue)), true)  // 设置默认选中
                })
            },
            //点击删除
            delCount(){
                if(this.multipleSelection.length < 1){
                    this.$message.error('请选择需要删除的账户');
                }else
                {
                    this.delVisible = true;
                }
            },
            bindLink(scope){
                this.curr_id = scope.orgId
                this.currUserId = scope.id
                this.getTreeData()
                this.bindVisible = true
                getUnassignedOrgList().then(res=>{
                    if(res.success){
                        this.unbindOrgs = res.datas
                        if( res.datas.length  == 0){
                            this.$message.error('暂无可划分的组织机构')
                        }
                    }else{
                        this.$message.error('暂无可划分的组织机构')
                    }
                })
            },
            bindOrgUser(){
                let checkedOrgs = this.$refs.tree.getCheckedNodes()
                if(checkedOrgs.length<1){
                    this.$message.error('请选择组织机构')
                    return false
                }
                if(checkedOrgs.length>1){
                    this.$message.error('一次只能划分一个组织机构')
                    return false
                }
                assignOrgToUser({
                    flag:1,
                    orgId:checkedOrgs[0].id,
                    userId:this.currUserId
                }).then(res=>{
                    if(res.success){
                        this.$message.success(res.message)
                        this.bindVisible = false
                        this.getData()
                    }else{
                        this.$message.error(res.message)
                    }
                })
            },
            unbindBtn(scope){
                this.unbindVisible = true
                this.unbindIfo = scope
            },
            unbindLink(){
                this.curr_id = ''
                assignOrgToUser({
                    flag:0,
                    orgId:this.unbindIfo.orgId,
                    userId:this.unbindIfo.id
                }).then(res=>{
                    if(res.success){
                        this.$message.success(res.message)
                        this.getData()
                    }else{
                        this.$message.error(res.message)
                    }
                    this.unbindVisible = false
                })
            },
            //格式化用户所属的组织机构
            formatOrg(row, column, cellValue, index){
                const treeData =  this.tagsList
                let treeItem = null
                const repeatTreeData = (td) =>{
                    for(let i=0;i<td.length;i++){
                        if(td[i].id == cellValue){
                            treeItem = td[i]
                            return
                        }else{
                            if(td[i].children && td[i].children.length>0){
                                repeatTreeData(td[i].children)
                            }
                        }
                    }
                }
                repeatTreeData(treeData)
                return treeItem ? treeItem.orgName : '--'
            },
            bindLinkEqu(scope){
                if(scope.orgId || scope.roleValue == 8){
                    this.isShowDivision = true
                    this.parentData = [scope]
                }else{
                    this.$message.error("请先划分组织机构");
                }

            },
            //多选框切换
            styleSelectionChange(val){
                console.log(val)
                var selectArr = []
                for(var i=0;i<val.length;i++){
                    if(val[i]){
                        selectArr.push(val[i])
                    }
                }
                this.styleSelection = selectArr;
                console.log(this.styleSelection)
            },
            //必填字段校验
            formValidate(formname){
                if(formname.account&&formname.pwd&&formname.name&&formname.phone&&formname.email){
                    if(!regPhoneNum(formname.phone)){
                        this.$message.error("手机号码有误，请重填");
                        return false;
                    }
                    if(!regEmailNum(formname.email)){
                        this.$message.error("邮箱格式不正确，请重填");
                        return false;
                    }
                    return true;
                }else{
                    if(!formname.account){
                        this.$message.error('请输入账号名称');
                        return false;
                    }
                    if(!formname.pwd){
                        this.$message.error('请输入密码');
                        return false;
                    }
                    if(!formname.name){
                        this.$message.error('请输入姓名');
                        return false;
                    }
                    if(!formname.phone){
                        this.$message.error('请输入手机号');
                        return false;
                    }
                    if(!formname.email){
                        this.$message.error('请输入邮箱');
                        return false;
                    }
                }
            }
        }
    }
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .del-dialog-cnt{
        font-size: 16px;
        text-align: center
    }
    .table{
        width: 100%;
        font-size: 14px;
    }
    .red{
        color: #ff0000;
    }
    .mr10{
        margin-right: 10px;
    }
    .limit-width{
        width: 30%;
        float: left;
        margin:0 10% 10px;

    }
    .el-form-item::after, .el-form-item::before {
        clear: both;
    }
</style>
